<template>
  <div class="app-container">

    <!-- 表头 查询与新增 -->
    <el-row>
      <el-col :span="24">
        <div class="filter-container">
          <el-input v-model="listQuery.query" placeholder="用户昵称" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter"/>
          <el-input v-model="listQuery.userTel" placeholder="用户电话" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter"/>
          <el-date-picker
            v-model="buyTime"
            class="filter-item"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"/>
          <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
        </div>
      </el-col>
    </el-row>

    <!-- 表格list -->
    <el-row>
      <el-col :span="24" :gutter="24">
        <el-table
          v-loading="listLoading"
          :key="tableKey"
          :data="list"
          :height="tableHeight"
          element-loading-text="Loading"
          border
          fit
          style="width: 100%;"
          highlight-current-row>
          <el-table-column align="center" label="序号" width="80">
            <template slot-scope="scope">
              {{ scope.$index }}
            </template>
          </el-table-column>
          <el-table-column label="用户昵称" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.nickName }}
            </template>
          </el-table-column>
          <el-table-column label="等级名称" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.userRankName }}
            </template>
          </el-table-column>
          <el-table-column label="当前积分" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.userPoints }}
            </template>
          </el-table-column>
          <el-table-column label="用户电话" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.userTel }}
            </template>
          </el-table-column>
          <el-table-column label="账户余额" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.moneyBalance }}
            </template>
          </el-table-column>
          <el-table-column label="是否关注" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.followFlag }}
            </template>
          </el-table-column>
          <el-table-column label="关注时间" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.followTime | timeFilter }}
            </template>
          </el-table-column>
          <el-table-column label="创建时间" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.createdTime | timeFilter }}
            </template>
          </el-table-column>
          <el-table-column label="修改时间" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.modifiedTime | timeFilter }}
            </template>
          </el-table-column>
          <el-table-column label="最后登录时间" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.lastLoginTime | timeFilter }}
            </template>
          </el-table-column>
          <el-table-column label="用户姓名" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.userName }}
            </template>
          </el-table-column>
          <el-table-column label="用户性别" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.userSex }}
            </template>
          </el-table-column>
          <el-table-column label="出生日期" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.birthDay | timeFilter }}
            </template>
          </el-table-column>
          <!--<el-table-column label="默认卡类型" show-overflow-tooltip style="width: 10%" align="center">-->
            <!--<template slot-scope="scope">-->
              <!--{{ scope.row.defaultCard }}-->
            <!--</template>-->
          <!--</el-table-column>-->
          <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="primary" @click="showBonus(scope.row)">
                发送红包
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="listQuery.pageNum"
          :limit.sync="listQuery.pageSize"
          layout="total, sizes, prev, pager, next"
          style="float:right;"
          @pagination="fetchData"/>
      </el-col>
    </el-row>

    <!-- 编辑弹窗 -->
    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="right"
        label-width="100px"
        style="">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户昵称" label-width="105px" prop="nickName">
              <el-input v-model="temp.nickName"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户头像" label-width="105px" prop="headImg">
              <el-input v-model="temp.headImg"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="等级名称" label-width="105px" prop="userRankName">
              <el-input v-model="temp.userRankName"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="当前积分" label-width="105px" prop="userPoints">
              <el-input v-model="temp.userPoints"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户级别" label-width="105px" prop="userLevel">
              <el-input v-model="temp.userLevel"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户电话" label-width="105px" prop="userTel">
              <el-input v-model="temp.userTel"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="支付账户" label-width="105px" prop="payNo">
              <el-input v-model="temp.payNo"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="账户余额" label-width="105px" prop="moneyBalance">
              <el-input v-model="temp.moneyBalance"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="是否关注" label-width="105px" prop="followFlag">
              <el-input v-model="temp.followFlag"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="关注时间" label-width="105px" prop="followTime">
              <el-input v-model="temp.followTime"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户姓名" label-width="105px" prop="userName">
              <el-input v-model="temp.userName"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户性别" label-width="105px" prop="userSex">
              <el-input v-model="temp.userSex"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="出生日期" label-width="105px" prop="birthDay">
              <el-input v-model="temp.birthDay"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="有效标志" label-width="105px">
              <el-switch
                v-model="validSwitch"
                active-color="#13ce66"
                inactive-color="#ff4949"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">确认</el-button>
        <el-button @click="dialogFormVisible = false">取消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :visible.sync="dialogPointFormVisible"
      title="积分流水">
      <el-row>
        <el-col :span="24" :gutter="24">
          <el-table
            :data="pointListData"
            :height="tableHeight"
            element-loading-text="Loading"
            border
            fit
            style="width: 100%;"
            highlight-current-row>
            <el-table-column align="center" label="序号" width="80">
              <template slot-scope="scope">
                {{ scope.$index }}
              </template>
            </el-table-column>
            <el-table-column label="获取积分" show-overflow-tooltip style="width: 10%" align="center">
              <template slot-scope="scope">
                {{ scope.row.points }}
              </template>
            </el-table-column>
            <el-table-column label="获取方式" show-overflow-tooltip style="width: 10%" align="center">
              <template slot-scope="scope">
                {{ scope.row.way }}
              </template>
            </el-table-column>
            <el-table-column label="描述信息" show-overflow-tooltip style="width: 10%" align="center">
              <template slot-scope="scope">
                {{ scope.row.desc1 }}
              </template>
            </el-table-column>
            <el-table-column label="获取业务编号" show-overflow-tooltip style="width: 10%" align="center">
              <template slot-scope="scope">
                {{ scope.row.businessKey }}
              </template>
            </el-table-column>
            <el-table-column label="创建时间" show-overflow-tooltip style="width: 10%" align="center">
              <template slot-scope="scope">
                {{ scope.row.createTime }}
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-show="pointListTotal>0"
            :total="pointListTotal"
            :page.sync="pointListQuery.pageNum"
            :limit.sync="pointListQuery.pageSize"
            layout="total, sizes, prev, pager, next"
            style="float:right;"
            @pagination="getUserPoint"/>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogPointFormVisible = false">取消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :visible.sync="dialogBonusFormVisible"
      title="发送红包">
      <el-form
        ref="dataForm3"
        :rules="rules3"
        :model="bonusTemp"
        label-position="right"
        label-width="100px"
        style="">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="红包名称" label-width="150px" prop="bonusName">
              <el-input v-model="bonusTemp.bonusName"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="红包所值金额" label-width="150px" prop="bonusMoney">
              <el-input v-model.number="bonusTemp.bonusMoney"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="订单最少金额" label-width="150px" prop="minGoodsAmount">
              <el-input v-model.number="bonusTemp.minGoodsAmount"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="红包有效期" label-width="150px" prop="expireTime">
              <el-radio-group v-model="selectExpireType">
                <el-radio v-for="item in expireOptions" :key="item.id" :label="item.id" @change="changeExpireType">{{
                  item.text }}
                </el-radio>
              </el-radio-group>
              <el-input-number v-show="isShow" v-model="selectExpireDay" :min="1" controls-position="right"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="红包可用产品" label-width="150px" prop="useGoods">
              <el-transfer v-model="selectUseGoods" :props="{key: 'pid',label: 'pname'}" :data="productData"/>
              <span style="color: red">没选为所有产品可用</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="排序" label-width="150px" prop="sort">
              <el-input v-model.number="bonusTemp.sort"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addBonus()">确认</el-button>
        <el-button @click="dialogBonusFormVisible = false">取消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import sxProductBasicInfoApi from '@/api/manage/SxProductBasicInfoApi'
import SxUserInfoApi from '@/api/manage/SxUserInfoApi'
  import SxBonusRecordApi from '@/api/manage/SxBonusRecordApi';
import SxUserScoreRecordApi from '@/api/manage/SxUserScoreRecordApi'
import waves from '@/directive/waves' // Waves directive
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
export default {
  directives: { waves },
  components: { Pagination },
  filters: {
    statusFilter(status) {
      const statusMap = {
        1: 'success',
        2: 'gray',
        0: 'danger'
      }
      return statusMap[status]
    },
    validFilter(status) {
      const statusMap = {
        1: '有效',
        0: '作废'
      }
      return statusMap[status]
    },
    timeFilter(time) {
      if (time) {
        return new Date(time).Format('yyyy-MM-dd hh:mm:ss')
      } else {
        return ''
      }
    }
  },
  data() {
    return {
      tableKey: 0, // 表格key值
      list: null, // 表格对象
      listLoading: true, // 表格加载框
      total: 0, // 分页总数
      buyTime: '',
      tableHeight: window.innerHeight - 220, // 表格高度
      listQuery: { // 表格查询对象
        pageNum: 1,
        pageSize: 10,
        query: '',
        validFlag: undefined,
        userTel: '',
        userId: ''
      },
      temp: {}, // 编辑框临时变量
      statusOptions: { // 有效无效下拉框
        '1': '有效',
        '0': '作废'
      },
      dialogFormVisible: false, // 编辑框显示
      dialogStatus: '', // 编辑框更新插入状态
      textMap: { // 编辑框标题
        update: '编辑',
        create: '创建'
      },
      rules: { // 编辑框校验规则
        sxUserInfoName: [{ required: true, message: 'SX用户信息表名称', trigger: 'change' }]
      },
      pointListQuery: { // 表格查询对象
        pageNum: 1,
        pageSize: 10,
        userId: ''
      },
      pointListData: [],
      dialogPointFormVisible: false,
      pointListTotal: 0,
      dialogBonusFormVisible: false,
      bonusTemp: {},
      productData: [],
      selectUseGoods: [],
      isShow: false,
      selectExpireType: 3,
      selectExpireDay: 30,
      expireOptions: [
        {id: 1, text: '7天', expireDay: 7},
        {id: 2, text: '15天', expireDay: 15},
        {id: 3, text: '一个月', expireDay: 30},
        {id: 4, text: '三个月', expireDay: 90},
        {id: 5, text: '半年', expireDay: 180},
        {id: 6, text: '一年', expireDay: 365},
        {id: 7, text: '其他', expireDay: 0}
      ],
      rules3: { // 编辑框校验规则
        bonusName: [{ required: true, message: '红包管理名称', trigger: 'change' }],
        bonusMoney: [{ required: true, message: '红包金额', trigger: 'change' }],
        minGoodsAmount: [{ required: true, message: '红包订单金额', trigger: 'change' }],
        expireTime: [{ required: true, message: '红包过期时间', trigger: 'change' }],
      }
    }
  },
  computed: {
    validSwitch: {
      // getter
      get: function() {
        return this.temp.validFlag === '1'
      },
      // setter
      set: function(newValue) {
        if (newValue) {
          this.temp.validFlag = '1'
        } else {
          this.temp.validFlag = '0'
        }
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    changeExpireType(id) {
      if (id === 7) {
        this.isShow = true
      } else {
        this.isShow = false
        const expireOption = this.$_.find(this.expireOptions, (o) => {
          return o.id === id
        })
        this.selectExpireDay = expireOption.expireDay
      }
    },
    addBonus() {
      const that = this
      this.bonusTemp.useGoods = JSON.stringify(this.selectUseGoods)
      this.$refs['dataForm3'].validate((valid) => {
        if (valid) {
          SxBonusRecordApi.addUserBonus(this.bonusTemp).then(() => {
            this.dialogBonusFormVisible = false
            this.$notify({
              title: '成功',
              message: '添加成功',
              type: 'success',
              duration: 1000,
              onClose() {
                that.fetchData()
              }
            })
          })
        }
      })
    },
    /**
     * 获取顶级结点
     * */
    getRootData() {
      sxProductBasicInfoApi.getRootData({ r: Math.random() }).then((data) => {
        this.productData = data
      })
    },
    showBonus(row) {
      this.dialogBonusFormVisible = true
      this.restBonusTemp()
      this.bonusTemp.userId = row.userId
      this.getRootData()
      this.selectExpireDay = 30
      this.selectExpireType = 3
    },
    showPoint(row) {
      this.pointListQuery.userId = row.userId
      this.getUserPoint()
      this.dialogPointFormVisible = true
    },
    getUserPoint() {
      SxUserScoreRecordApi.getPage(this.pointListQuery).then(data => {
        this.pointListData = data.rows
        this.pointListTotal = data.total
      })
    },

    /**
       * 导出用户信息按钮
       */
    exportReport() {
      // 创建一个 form
      var form1 = document.createElement('form')
      form1.id = 'form1'
      form1.name = 'form1'

      // 添加到 body 中
      document.body.appendChild(form1)

      // 创建一个输入
      var input = document.createElement('input')
      // 设置相应参数
      input.type = 'text'
      input.name = 'query'
      input.value = this.listQuery.query

      // 创建一个输入
      var input1 = document.createElement('input')
      // 设置相应参数
      input1.type = 'text'
      input1.name = 'times'
      if (this.buyTime && this.buyTime.length > 0) {
        input1.value = JSON.stringify(this.buyTime)
      } else {
        input1.value = null
      }

      // 将该输入框插入到 form 中
      form1.appendChild(input)
      form1.appendChild(input1)

      // form 的提交方式
      form1.method = 'POST'
      // form 提交路径
      form1.action = this.exportUrl

      // 对该 form 执行提交
      form1.submit()
      // 删除该 form
      document.body.removeChild(form1)
    },

    /**
       * 获取表格数据
       */
    fetchData() {
      const that = this
      this.listLoading = true
      if (this.buyTime && this.buyTime.length > 0) {
        this.listQuery.times = JSON.stringify(this.buyTime)
      } else {
        this.listQuery.times = null
      }
      this.$http.all([SxUserInfoApi.getPage(this.listQuery)])
        .then(this.$http.spread(function(perms) {
          that.list = perms.rows
          that.total = perms.total
          that.listLoading = false
        }))
    },
    /**
       * 新增弹窗
       */
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    restBonusTemp() {
      this.bonusTemp = {
        id: '',
        bonusName: '',
        bonusType: '',
        bonusMoney: 0,
        useGoods: '',
        sendType: 0,
        minGoodsAmount: 0,
        bonusNumber: 0,
        bonusImg: '',
        expireTime: new Date().add('dayofyear', 30, true).getTime(),
        sort: 1,
        userId: ''
      }
    },
    /**
       * 清空弹窗内容
       */
    resetTemp() {
      this.temp = {
        userId: '',
        minOpenId: '',
        openId: '',
        unionId: '',
        nickName: '',
        headImg: '',
        userRankId: '',
        userRankName: '',
        userPoints: '',
        userLevel: '',
        userTel: '',
        payNo: '',
        moneyBalance: '',
        followFlag: '',
        followTime: '',
        createdTime: '',
        modifiedTime: '',
        lastLoginTime: '',
        userPw: '',
        userName: '',
        userSex: '',
        birthDay: '',
        defaultCard: '',
        validFlag: '1'
      }
    },
    /**
       * 确定新增
       */
    createData() {
      const that = this
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          SxUserInfoApi.insert(this.temp).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 1000,
              onClose() {
                that.fetchData()
              }
            })
          })
        }
      })
    },
    /**
       * 编辑弹窗
       */
    handleUpdate(row) {
      this.temp = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    /**
       * 确认编辑
       */
    updateData() {
      const that = this
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          SxUserInfoApi.update(tempData).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 1000,
              onClose() {
                that.fetchData()
              }
            })
          })
        }
      })
    },
    /**
       * 删除操作
       */
    handleDelete(row) {
      const that = this
      SxUserInfoApi.remove({ userId: row.userId }).then(() => {
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 1000,
          onClose() {
            that.fetchData()
          }
        })
      })
    },
    /**
       * 搜索过滤
       */
    handleFilter() {
      this.listQuery.pageNum = 1
      this.fetchData()
    }
  },
  watch: {
    selectExpireDay(val) {
      let now = new Date()
      now = now.add('dayofyear', val, true)
      this.bonusTemp.expireTime = now.getTime()
    }
  }
}
</script>
